<template>
  <div class="customer-container">
    <!-- 搜索表单 -->
    <el-card class="search-card">
      <el-form :model="searchForm" inline>
        <el-form-item label="客户姓名">
          <el-input v-model="searchForm.name" placeholder="请输入客户姓名" clearable />
        </el-form-item>
        <el-form-item label="手机号码">
          <el-input v-model="searchForm.phone" placeholder="请输入手机号码" clearable />
        </el-form-item>
        <el-form-item label="证件号码">
          <el-input v-model="searchForm.idCard" placeholder="请输入证件号码" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>查询
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>重置
          </el-button>
          <el-button type="success" @click="handleAdd">
            <el-icon><Plus /></el-icon>新增
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 数据表格 -->
    <el-card class="table-card">
      <el-table
        v-loading="loading"
        :data="tableData"
        border
        style="width: 100%"
      >
        <el-table-column type="index" label="序号" width="60" align="center" />
        <el-table-column prop="name" label="客户姓名" min-width="100" />
        <el-table-column prop="phone" label="手机号码" min-width="120" />
        <el-table-column prop="idCard" label="证件号码" min-width="180" />
        <el-table-column prop="gender" label="性别" width="80" align="center">
          <template #default="{ row }">
            {{ row.gender === 1 ? '男' : '女' }}
          </template>
        </el-table-column>
        <el-table-column prop="age" label="年龄" width="80" align="center" />
        <el-table-column prop="address" label="居住地址" min-width="200" show-overflow-tooltip />
        <el-table-column prop="status" label="状态" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="row.status === 1 ? 'success' : 'danger'">
              {{ row.status === 1 ? '正常' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" min-width="160" show-overflow-tooltip />
        <el-table-column label="操作" width="280" fixed="right">
          <template #default="{ row }">
            <div class="operation-buttons">
              <el-button link type="primary" @click="handleEdit(row)">
                <el-icon><Edit /></el-icon>编辑
              </el-button>
              <el-button link type="primary" @click="handleView(row)">
                <el-icon><View /></el-icon>查看
              </el-button>
              <el-button 
                link 
                :type="row.status === 1 ? 'danger' : 'success'"
                @click="handleToggleStatus(row)"
              >
                {{ row.status === 1 ? '禁用' : '启用' }}
              </el-button>
              <el-button link type="danger" @click="handleDelete(row)">
                <el-icon><Delete /></el-icon>删除
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="page.current"
          v-model:page-size="page.size"
          :total="page.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      v-model="dialog.visible"
      :title="dialog.type === 'add' ? '新增客户' : '编辑客户'"
      width="600px"
      append-to-body
      destroy-on-close
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="客户姓名" prop="name">
          <el-input v-model="form.name" placeholder="请输入客户姓名" />
        </el-form-item>
        <el-form-item label="手机号码" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入手机号码" />
        </el-form-item>
        <el-form-item label="证件号码" prop="idCard">
          <el-input v-model="form.idCard" placeholder="请输入证件号码" />
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-radio-group v-model="form.gender">
            <el-radio :label="1">男</el-radio>
            <el-radio :label="2">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="年龄" prop="age">
          <el-input-number v-model="form.age" :min="1" :max="150" />
        </el-form-item>
        <el-form-item label="居住地址" prop="address">
          <el-input v-model="form.address" type="textarea" placeholder="请输入居住地址" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialog.visible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>

    <!-- 查看对话框 -->
    <el-dialog
      v-model="viewDialog.visible"
      title="客户详情"
      width="600px"
      append-to-body
    >
      <el-descriptions :column="2" border>
        <el-descriptions-item label="客户姓名">{{ viewData.name }}</el-descriptions-item>
        <el-descriptions-item label="手机号码">{{ viewData.phone }}</el-descriptions-item>
        <el-descriptions-item label="证件号码">{{ viewData.idCard }}</el-descriptions-item>
        <el-descriptions-item label="性别">{{ viewData.gender === 1 ? '男' : '女' }}</el-descriptions-item>
        <el-descriptions-item label="年龄">{{ viewData.age }}</el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag :type="viewData.status === 1 ? 'success' : 'danger'">
            {{ viewData.status === 1 ? '正常' : '禁用' }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="居住地址" :span="2">{{ viewData.address }}</el-descriptions-item>
        <el-descriptions-item label="创建时间" :span="2">{{ viewData.createTime }}</el-descriptions-item>
      </el-descriptions>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh, Plus, Edit, Delete, View } from '@element-plus/icons-vue'
import { customerApi } from '@/api/customer'

// 搜索表单
const searchForm = reactive({
  name: '',
  phone: '',
  idCard: ''
})

// 表格数据
const loading = ref(false)
const tableData = ref([
  {
    id: 1,
    name: '张三',
    phone: '13800138000',
    idCard: '110101199001011234',
    gender: 1,
    age: 32,
    address: '北京市朝阳区某某街道某某小区',
    status: 1,
    createTime: '2024-01-01 12:00:00'
  },
  {
    id: 2,
    name: '李四',
    phone: '13900139000',
    idCard: '110101199002022345',
    gender: 2,
    age: 28,
    address: '北京市海淀区某某街道某某小区',
    status: 1,
    createTime: '2024-01-02 12:00:00'
  }
])

// 分页
const page = reactive({
  current: 1,
  size: 10,
  total: 2
})

// 表单对话框
const dialog = reactive({
  visible: false,
  type: 'add' // add or edit
})

const formRef = ref(null)
const form = reactive({
  name: '',
  phone: '',
  idCard: '',
  gender: 1,
  age: 18,
  address: ''
})

const rules = {
  name: [
    { required: true, message: '请输入客户姓名', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号码', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  idCard: [
    { required: true, message: '请输入证件号码', trigger: 'blur' },
    { pattern: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/, message: '请输入正确的身份证号码', trigger: 'blur' }
  ],
  gender: [
    { required: true, message: '请选择性别', trigger: 'change' }
  ],
  age: [
    { required: true, message: '请输入年龄', trigger: 'blur' }
  ],
  address: [
    { required: true, message: '请输入居住地址', trigger: 'blur' }
  ]
}

// 查看对话框
const viewDialog = reactive({
  visible: false
})
const viewData = ref({})

// 初始化页面数据
onMounted(() => {
  fetchCustomerList()
})

// 获取客户列表数据
const fetchCustomerList = () => {
  loading.value = true
  const params = {
    pageNum: page.current,
    pageSize: page.size,
    ...searchForm
  }
  
  customerApi.getList(params).then(res => {
    tableData.value = res.data.rows
    page.total = res.data.total
    loading.value = false
  }).catch(() => {
    loading.value = false
  })
}

// 搜索
const handleSearch = () => {
  page.current = 1
  fetchCustomerList()
}

// 重置
const handleReset = () => {
  searchForm.name = ''
  searchForm.phone = ''
  searchForm.idCard = ''
  page.current = 1
  fetchCustomerList()
}

// 新增
const handleAdd = () => {
  dialog.type = 'add'
  dialog.visible = true
  form.name = ''
  form.phone = ''
  form.idCard = ''
  form.gender = 1
  form.age = 18
  form.address = ''
}

// 编辑
const handleEdit = (row) => {
  dialog.type = 'edit'
  dialog.visible = true
  Object.assign(form, row)
}

// 查看
const handleView = (row) => {
  viewDialog.visible = true
  viewData.value = row
}

// 切换状态
const handleToggleStatus = (row) => {
  const action = row.status === 1 ? '禁用' : '启用'
  ElMessageBox.confirm('确认要' + action + '该客户吗？', '提示', {
    type: 'warning'
  }).then(() => {
    const data = {
      custId: row.id,
      status: row.status === 1 ? 0 : 1
    }
    
    customerApi.updateStatus(data).then(() => {
      ElMessage.success(action + '成功')
      fetchCustomerList()
    })
  }).catch(() => {})
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    
    loading.value = true
    if (dialog.type === 'add') {
      // 新增客户
      await customerApi.add(form)
      ElMessage.success('新增客户成功')
    } else {
      // 编辑客户
      await customerApi.update(form)
      ElMessage.success('修改客户成功')
    }
    
    dialog.visible = false
    fetchCustomerList()
  } catch (error) {
    console.error('表单验证失败', error)
  } finally {
    loading.value = false
  }
}

// 删除客户
const handleDelete = (row) => {
  ElMessageBox.confirm('确认要删除该客户吗？此操作不可恢复！', '提示', {
    type: 'warning'
  }).then(() => {
    customerApi.delete(row.id).then(() => {
      ElMessage.success('删除成功')
      fetchCustomerList()
    })
  }).catch(() => {})
}

// 处理分页变化
const handleCurrentChange = (val) => {
  page.current = val
  fetchCustomerList()
}

const handleSizeChange = (val) => {
  page.size = val
  page.current = 1
  fetchCustomerList()
}
</script>

<style scoped>
.customer-container {
  padding: 20px;
}

.search-card {
  margin-bottom: 20px;
}

.table-card {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.operation-buttons {
  display: flex;
  align-items: center;
  flex-wrap: nowrap;
}

.operation-buttons .el-button {
  margin-right: 5px;
}
</style> 